package keter.web.util;

import keter.dao.CodeListDao;
import keter.dao.org.AccountDao;
import keter.domain.Account;
import keter.domain.CodeList;
import keter.util.AccountUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.transaction.annotation.Transactional;

/**
 * This class programatically populates the database at application startup. You
 * may probably wish to disable it in a production environment.
 * 
 * @author Daniel
 * 
 */
public class DbInit implements ApplicationListener<ContextRefreshedEvent> {

	private static final Logger logger = LoggerFactory.getLogger(DbInit.class);

	@Autowired
	private AccountDao userDao;
	
	@Autowired
	private CodeListDao cDao;

	private boolean alreadyInitialized = false;

	@Transactional
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (alreadyInitialized) {
			return;
		}
		if (userDao.findAll().size() > 0) {
			logger.info("系统已被初始化或用户数据已存在。");
			//测试分页 结论：hibernate可以为mysql添加“limit”语句
			userDao.findByName("haha");
			return;
		}
		Account admin = AccountUtil.buildAdmin();
		userDao.save(admin);

		Account user = AccountUtil.buildTeacherAccount("teacher");
		userDao.save(user);	
		
		initCodeList();
		
		alreadyInitialized = true;
		logger.info("系统数据初始化完毕！");
	}
	
	/**
	 * <p>Method ：initCodeList
	 * <p>Description : 初始化代码表
	 * 
	 * @author  顾力行-gulx@neusoft.com
	 */
	private void initCodeList(){
		CodeList entity = new CodeList(); 
		entity.setCodeKind("user.type");
		entity.setCodeValue("teacher");
		entity.setCodeName("教师");
		entity.setCodeValue("TEACHER");
		cDao.save(entity);
		
		entity = new CodeList(); 
		entity.setCodeKind("user.type");
		entity.setCodeValue("student");
		entity.setCodeName("学生");
		entity.setCodeValue("STUDENT");
		cDao.save(entity);
	}
	
}